<template>
  <div class="container">
    <!-- 新增弹窗 -->
    <el-dialog
      :title="formModel.id ? '修改学科' : '新增学科'"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog"
      @open="openDialog"
    >
      <!-- 表单区域 -->
      <el-form
        :model="formModel"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="formModel.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            :inactive-value="0"
            :active-value="1"
            v-model="formModel.isFrontDisplay"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('close-dialog')">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { update, add, detail } from '@/api/hmmm/subjects.js'
export default {
  name: 'abc',
  props: {
    dialogVisible: {
      type: Boolean,
      require: true
    },
    isId: {
      type: [String, Number],
      require: true
    }
  },
  data () {
    return {
      // 表单数据
      formModel: {
        name: '',
        subjectName: ''
      },
      // 表单自定义校验规则
      formRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    isid (newId) {
      this.isid = newId
    }
  },
  methods: {
    // 点击X和蒙版关闭弹窗
    closeDialog () {
      // 触发自定义事件，通知父组件去关闭弹窗
      this.$emit('close-dialog')
      // 清空表单内容
      this.$refs.formRef.resetFields()
      // 手动清空表单内容
      this.formModel = {
        subjectName: '',
        isFrontDisplay: '' // 权限启用标识
      }
    },
    // 点击确认添加
    submit () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // 校验成功
        if (this.formModel.id) {
          // 编辑
          await update(this.formModel)
        } else {
          // 添加
          await add({
            subjectName: this.formModel.subjectName,
            isFrontDisplay: this.formModel.isFrontDisplay
          })
        }
        // 提示用户
        const msg = this.formModel.id ? '编辑成功' : '添加成功'
        this.$message.success(msg)
        // 刷新表单数据
        // this.getDataList()
        this.$emit('get-datalist')
        // 关闭弹框
        this.$emit('close-dialog')
      })
    },
    // 弹窗打开触发事件 调取详细数据
    async openDialog () {
      // console.log(this.isId)
      // 调取接口获取详细数据
      const res = await detail(this.isId)
      // console.log(res)
      this.formModel = res.data
    }
  }
}
</script>

<style scoped lang="less"></style>
